package
{
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.net.FileReference;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.ui.Keyboard;
	
	import net.P2p;
	import net.decoder.DecoderClient;
	
	import netEvent.P2pEvent;
	
	public class Test extends Sprite
	{
		public static var sta:Stage;
		
		private var p2p:P2p;
		
		public static var t:TextField;
		public static var input:TextField;
		
		private var decoder:DecoderClient;
		
		public function Test()
		{
			sta = stage;
			
			decoder = new DecoderClient;
			
			t = new TextField();
			t.width = 500;
			t.height = 20;
			t.border = true;
			t.multiline=true;
			addChild(t);
			
			input = new TextField();
			input.width = 300;
			input.height = 20;
			input.border = true;
			input.type = TextFieldType.INPUT;
			addChild(input);
			
			var bt:Sprite = new Sprite();
			bt.buttonMode=true;
			bt.graphics.beginFill(0xff9900);
			bt.graphics.drawRect(0,0,95,20);
			bt.addEventListener(MouseEvent.CLICK,onClick);
			addChild(bt);
			
			input.y = 25;
			bt.x = input.width+5;
			bt.y = input.y;
			
			p2p = new P2p;
			p2p.addEventListener(P2pEvent.CONNECTED_TO_SERVER,onConnected);
		}
		
		private function onConnected(e:P2pEvent):void
		{
			p2p.addEventListener(P2pEvent.GROUP_CONNECTED,setup);
			p2p.type=P2p.GROUP_MEMBER;
			
		}
		private function setup(e:P2pEvent):void
		{
			p2p.removeEventListener(P2pEvent.GROUP_CONNECTED,setup);
			
			stage.addEventListener(KeyboardEvent.KEY_DOWN,testKey);
			stage.addEventListener(MouseEvent.DOUBLE_CLICK,move);
			stage.doubleClickEnabled = true;
		}
		
		private function move(e:MouseEvent):void
		{
			if(p2p.type==P2p.SERVER||p2p.type==P2p.GROUP_MEMBER)decoder["move"]([mouseX,mouseY]);
			p2p.sendMessage("move",[mouseX,mouseY]);
		}
		
		private function testKey(e:KeyboardEvent):void
		{
			switch(e.keyCode)
			{
				case Keyboard.SPACE:
					p2p.type=P2p.SERVER;
					t.text = p2p.peerID;
					break;
				
				case Keyboard.ESCAPE:
					p2p.type=P2p.NONE;
					break;
				
				case Keyboard.SHIFT:
					p2p.type=P2p.GROUP_MEMBER;
					break;
				
				default:
					break;
			}
		}
		
		private function onClick(e:MouseEvent):void
		{
			p2p.type = P2p.CLIENT;
			p2p.connectToServer(input.text);
			t.text = p2p.peerID;
		}
	}
}